local tbl_name = "user_data"
local load_sql = "SELECT `context`, `chksum` FROM `%s` WHERE path = '%s' AND name = '%s' AND branch = '%s'"
local save_sql = "REPLACE INTO `%s` (`update_time`, `path`, `name`, `branch`, `context`, `chksum`) VALUES ('%s', '%s', '%s', '%s', '%s', '%s');"

local M = {}

---! 数据加载
function M.load(conn, msg)
    local path, name, branch = table.unpack(msg.data)
    local cmd = string.format(load_sql, tbl_name, tostring(path or ""), tostring(name or ""), tostring(branch or ""))

    local cur = conn:execute(cmd)
    local row = cur:fetch({}, "a")
    cur:close()

    local context = row and row.context or ""
    local chksum = row and row.chksum or ""
    spdlog.debug("data", "user.load cmd = %s, context = %s, chksum = %s", cmd, context, chksum)

    return {context, chksum}
end

---! 数据保存
function M.save(conn, msg)
    local path, name, branch, context,chksum  = table.unpack(msg.data)
    local cmd = string.format(save_sql, tbl_name, os.date("%Y-%m-%d %H:%M:%S"),
                     tostring(path or ""),
                     tostring(name or ""),
                     tostring(branch or ""),
                     tostring(context or ""),
                     tostring(chksum or ""))

    local affected_rows = conn:execute(cmd)
    spdlog.debug("data", "user.save, cmd = %s, affected_rows = %d", cmd, affected_rows)

    return affected_rows > 0
end

return M
